package com.springboot.config.security.wx;

import com.springboot.config.security.JwtAuthorizationEntryPoint;
import com.springboot.config.security.NoPasswordEncoder;
import com.springboot.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/***
 *@descrition: spring-security配置类
 *@author: lzh
 */

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(101)
public class WxUserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    WxUserDetailsService wxUserDetailsService;

    @Autowired
    NoPasswordEncoder noPasswordEncoder;

    @Autowired
    JwtAuthorizationEntryPoint jwtAuthorizationEntryPoint;

    @Autowired
    MyAccessDeniedHandler wxUserAccessDeniedHandler;

    @Autowired
    WxUserAuthenticationTokenFilter wxUserAuthenticationTokenFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(wxUserDetailsService).passwordEncoder(noPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //关闭session管理
        http.csrf().disable().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().httpBasic().authenticationEntryPoint(jwtAuthorizationEntryPoint)
                .and().exceptionHandling().accessDeniedHandler(wxUserAccessDeniedHandler)
                .and().authorizeRequests().antMatchers(HttpMethod.GET, "/wx/login").permitAll()
                .antMatchers(HttpMethod.POST, "/wx/register").permitAll()
                .antMatchers("/wx/**").hasRole("WXUSER");
        http.addFilterBefore(wxUserAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


    }

}
